package com.uade.webservices;

import java.io.IOException;
import java.io.StringReader;
import java.util.Hashtable;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.uade.business.BusinessDelegate;
import com.uade.business.BusinessDelegateImpl;
import com.uade.model.Entrega;
import com.uade.xml.EntregaHandler;

@WebService
public class ServidorEstadoEntregaBean {

	private Logger log = Logger.getLogger(ServidorEstadoEntregaBean.class);

	@WebMethod
	public String notificarEntregaDespacho(String xml){
		try {
			log.info("Ingresa a notificarEntregaDespacho");
			Entrega entrega = parseXml(xml);
			if(entrega!=null){
				log.info("Se parseo correctamente el XML");
				BusinessDelegate busDel = BusinessDelegateImpl.getInstanace();
				return busDel.recepcionEstado(entrega.getEstado(), entrega.getCodigo());
			}else{
				return "Error";
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "Error";
		}
	}
	
	private Entrega parseXml(String xml) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		EntregaHandler handler = new EntregaHandler();
		try {
			SAXParser saxParser = factory.newSAXParser();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));

			saxParser.parse(is, handler);

		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		if(handler.getEntregaList()!=null && handler.getEntregaList().size()>0)
			return handler.getEntregaList().get(0);
		return null;
	}

}
